package com.ruleengine.coordinator;

import com.ruleengine.util.model.Message;
import com.ruleengine.worker.model.Chain;
import com.ruleengine.worker.rulechain.ChainManager;
import com.ruleengine.worker.runner.chain.ChainRunner;
import com.ruleengine.worker.runner.chain.ChainRunnerManager;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lianghanwei on 2024/3/20
 */
@Slf4j
public class SendWorkerClient implements IProducer {

    public static final String MESSAGE_LABELS_KEY_RULE_CHAIN_ID = "ruleChainId";

    private final ChainManager chainManager;
    private final ChainRunnerManager chainRunnerManager;

    public SendWorkerClient(ChainManager chainManager, ChainRunnerManager chainRunnerManager) {
        this.chainManager = chainManager;
        this.chainRunnerManager = chainRunnerManager;
    }

    // TODO-lhw-2024/03/21: chainManager 是不是只有一个 get 有用
    // TODO-lhw-2024/03/21: ChainRunnerManager 是不是只需要 getOrAddIfAbsent 保证

    public void send(Message item) {
        // 提取消息的 ruleChainId 信息
        String ruleChainId = item.getMetadata().getLabels().get(MESSAGE_LABELS_KEY_RULE_CHAIN_ID);

        // 尝试获取获取内存的 ruleChain 运行时
        ChainRunner chainRunner = chainRunnerManager.get(ruleChainId);

        // 没有则创建
        if (chainRunner == null) {
            // 查数据库最新配置（rule、ruleRelation），装配成 Chain
            Chain chain = chainManager.getChain(ruleChainId);

            if (chain == null) {
                log.warn("Rulechain not found, rulechainId={}", ruleChainId);
                return;
            }

            // 内存载入这个 ruleChain 运行时
            chainRunner = chainRunnerManager.getOrAddIfAbsent(chain);
        }

        // ruleChain 运行时处理这个消息
        chainRunner.process(item);
    }

    @Override
    public void close() {

    }
}
